import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:landlore/customWidget/iosStyleCalendar.dart';
import 'package:landlore/model/orderVO.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/model/roomCheckInOut.dart';
import 'package:mccounting_text/mccounting_text.dart';

import '../consts.dart';

class RecordBodyCheckIn extends StatelessWidget {
  final RoomCheckInOut orderVO;
  Function? callback;

  RecordBodyCheckIn({super.key, required this.orderVO, this.callback}) {}

  @override
  Widget build(BuildContext context) {
    bool titleOverFlow = (orderVO.roomNum!.length >= 6) ? true : false;

    // int tempEleAmount =
    //     orderVO.electricityAmount! - orderVO.electricityAmountLastMonth!;
    // int tempWaterAmount = orderVO.waterAmount! - orderVO.waterAmountLastMonth!;
    //
    // //处理使用量为负数的情况
    // //只有订单状态不是已出单的情况,才需要处理,否则直接显示数据库的结果
    // if (orderVO.state != OrderState.BILL_OUT) {
    //   if (tempEleAmount < 0) {
    //     if (Consts.NEGATIVE_BILL_CALCULATE_WAY) {
    //       tempEleAmount = 0;
    //       orderVO.electricityCharge = 0;
    //       //记录最终计算结果
    //       orderVO.electricityAmountResult = 0;
    //     } else {
    //       tempEleAmount = Consts().calculateBillFulSituation(
    //           orderVO.electricityAmountLastMonth!, orderVO.electricityAmount!);
    //       orderVO.electricityCharge =
    //           tempEleAmount * orderVO.electricityUnitPrice!;
    //
    //       orderVO.electricityAmountResult = tempEleAmount;
    //     }
    //   }
    //   if (tempWaterAmount < 0) {
    //     if (Consts.NEGATIVE_BILL_CALCULATE_WAY) {
    //       tempWaterAmount = 0;
    //       orderVO.waterCharge = 0;
    //       orderVO.waterAmountResult = 0;
    //     } else {
    //       tempWaterAmount = Consts().calculateBillFulSituation(
    //           orderVO.waterAmountLastMonth!, orderVO.waterAmount!);
    //       orderVO.waterCharge = tempWaterAmount * orderVO.waterUnitPrice!;
    //       orderVO.waterAmountResult = tempWaterAmount;
    //     }
    //   }
    // }

    return Container(
      padding: EdgeInsets.only(left: 10.w, right: 10.w, top: 20.h),
      color: Colors.grey,
      child: orderVO.state == null || orderVO.state == 0
          ? Text(
              '暂无可以信息',
              style: TextStyle(
                  fontFamily: '欢字卡通手书', fontSize: 50.sp, color: Colors.black),
            )
          : SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white70,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(30.r),
                          topRight: Radius.circular(30.r)),
                    ),
                    padding:
                        EdgeInsets.only(left: 20.w, right: 10.w, top: 10.h),
                    child: Row(
                      children: [
                        Expanded(
                            flex: 2,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  orderVO.roomNum!,
                                  style: Consts.titleText.copyWith(
                                      fontSize: titleOverFlow ? 45.sp : 65.sp),
                                ),
                                Text(
                                  orderVO.contact == null
                                      ? ''
                                      : orderVO.contact!,
                                  style: Consts.titleText.copyWith(
                                      fontSize: 25.sp,
                                      fontWeight: FontWeight.w600,
                                      fontFamily: '欢字卡通手书'),
                                ),
                                Text(
                                  '${orderVO.createDate!.year}年${orderVO.createDate!.month}月${orderVO.createDate!.day}日',
                                  style: Consts.titleText.copyWith(
                                      fontSize: 25.sp,
                                      fontWeight: FontWeight.w600,
                                      fontFamily: '欢字卡通手书'),
                                ),
                              ],
                            )),
                        Expanded(
                            flex: 1,
                            child: IosStyleCalendar(
                                year: orderVO.createDate!.year,
                                month: orderVO.createDate!.month))
                      ],
                    ),
                  ),
                  Container(
                    color: Colors.white70,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          '合计:',
                          style:
                              TextStyle(fontSize: 65.sp, fontFamily: '欢字卡通手书'),
                        ),
                        Expanded(
                          child: Center(
                            child: McCountingText(
                              begin: 0,
                              end: double.parse(getSum(orderVO)),
                              precision: 1,
                              style: TextStyle(
                                  fontSize: 60.sp, fontFamily: '欢字卡通手书'),
                              duration: const Duration(seconds: 1),
                              curve: Curves.fastOutSlowIn,
                            ),
                            // Text(
                            //   '${getSum(orderVO)}',
                            //   overflow: TextOverflow.visible,
                            //   style: TextStyle(fontSize: 60.sp),
                            // ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const Divider(
                    thickness: 5,
                    color: Colors.black,
                  ),
                  Container(
                    decoration: BoxDecoration(
                        color: const Color(0xff6c757d),
                        image: DecorationImage(
                            image:
                                const AssetImage('assets/images/crossword.png'),
                            repeat: ImageRepeat.repeat,
                            colorFilter: ColorFilter.mode(
                                Colors.black.withOpacity(0.8),
                                BlendMode.srcIn)),
                        borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(30.r),
                            bottomRight: Radius.circular(30.r))),
                    padding: EdgeInsets.only(left: 10.w, right: 10.w),
                    child: Column(
                      children: [
                        Center(
                          child: Text(
                            '下月部分',
                            style: TextStyle(
                                decoration: TextDecoration.none,
                                fontSize: 25.sp,
                                fontFamily: "欢字卡通手书",
                                color: Colors.black87),
                          ),
                        ),
                        itemWidget(
                          title: '租金',
                          price: orderVO.rent!.toStringAsFixed(0),
                        ),
                        itemWidget(
                          title: '附加费',
                          price: orderVO.otherCharge!.toStringAsFixed(0),
                        ),
                        Center(
                          child: Text(
                            '本月部分',
                            style: TextStyle(
                                decoration: TextDecoration.none,
                                fontSize: 25.sp,
                                fontFamily: "欢字卡通手书",
                                color: Colors.black87),
                          ),
                        ),
                        Center(
                          child: Text(
                            getWeightText(orderVO.createDate!),
                            style: TextStyle(
                                decoration: TextDecoration.none,
                                fontSize: 20.sp,
                                fontFamily: "欢字卡通手书",
                                color: Colors.black87),
                          ),
                        ),
                        itemWidget(
                          title: '租金',
                          price:
                              '${orderVO.rent!.toStringAsFixed(0)} × ${getDayOfTheMonthWeight(orderVO.createDate!).toStringAsFixed(2)} = ${(orderVO.rent! * getDayOfTheMonthWeight(orderVO.createDate!)).toStringAsFixed(1)} ',
                        ),
                        itemWidget(
                          title: '押金',
                          price: '${orderVO.deposit!.toStringAsFixed(0)}',
                        ),
                        itemWidget(
                          title: '附加费',
                          price: orderVO.otherCharge == 0
                              ? '0'
                              : '${orderVO.otherCharge!} × ${getDayOfTheMonthWeight(orderVO.createDate!).toStringAsFixed(2)} = ${(orderVO.otherCharge! * getDayOfTheMonthWeight(orderVO.createDate!)).toStringAsFixed(1)} ',
                        ),
                        //电表照片
                        orderVO.eleImage == null
                            ? const SizedBox()
                            : Column(
                              children: [
                                Center(
                                  child: Text(
                                    '初始电表',
                                    style: TextStyle(
                                        decoration: TextDecoration.none,
                                        fontSize: 30.sp,
                                        fontFamily: "欢字卡通手书",
                                        color: Colors.black87),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () async {
                                      await Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) => FullScreenImage(
                                                  imagePath: orderVO.eleImage!)));
                                    },
                                    child: Hero(
                                      tag: '${orderVO.eleImage}',
                                      child: Container(
                                          margin: EdgeInsets.all(10.h),
                                          decoration: BoxDecoration(
                                              color: Colors.black54,
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(20.r))),
                                          width: 350.w,
                                          height: 350.w,
                                          child: ClipRRect(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(20.r)),
                                              child: ThumbnailImage(
                                                  imagePath: orderVO.eleImage!))
                                          // Image.file(File(orderVO.eleImage!),
                                          //     fit: BoxFit.fitWidth),
                                          ),
                                    ),
                                  ),
                              ],
                            ),

                        //水表照片
                        orderVO.waterImage == null
                            ? const SizedBox()
                            : Column(
                              children: [
                                Center(
                                  child: Text(
                                    '初始水表',
                                    style: TextStyle(
                                        decoration: TextDecoration.none,
                                        fontSize: 30.sp,
                                        fontFamily: "欢字卡通手书",
                                        color: Colors.black87),
                                  ),
                                ),
                                GestureDetector(
                                    onTap: () async {
                                      await Navigator.push(
                                          context,
                                          MaterialPageRoute(
                                              builder: (context) => FullScreenImage(
                                                  imagePath: orderVO.waterImage!)));
                                    },
                                    child: Hero(
                                      tag: '${orderVO.waterImage}',
                                      child: Container(
                                          margin: EdgeInsets.all(10.h),
                                          decoration: BoxDecoration(
                                              color: Colors.black54,
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(20.r))),
                                          width: 350.w,
                                          height: 350.w,
                                          child: ClipRRect(
                                              borderRadius: BorderRadius.all(
                                                  Radius.circular(20.r)),
                                              child: ThumbnailImage(
                                                  imagePath: orderVO.waterImage!))
                                          // Image.file(File(orderVO.waterImage!),
                                          //     fit: BoxFit.fill),
                                          ),
                                    ),
                                  ),
                              ],
                            ),
                        SizedBox(
                          height: 20.h,
                        ),
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 10.h,
                  )
                ],
              ),
            ),
    );
  }

  getSum(RoomCheckInOut orderVO) {
    double weight = getDayOfTheMonthWeight(orderVO.createDate!);
    return (orderVO.rent! +
            orderVO.otherCharge! +
            orderVO.deposit! +
            (orderVO.rent! * weight) +
            (orderVO.otherCharge! * weight))
        .toStringAsFixed(1);
  }

  //获取当前月剩余天数
  int getRestDayOfTheMonth(DateTime date) {
    DateTime endOfMonth = DateTime(date.year, date.month + 1, 0); // 获取本月最后一天
    int remainingDays = endOfMonth.difference(date).inDays + 1; // 计算剩余天数，包括当天
    return remainingDays;
  }

  //获取当前月天数权重
  double getDayOfTheMonthWeight(DateTime date) {
    DateTime endOfMonth = DateTime(date.year, date.month + 1, 0); // 获取本月最后一天
    int remainingDays = endOfMonth.difference(date).inDays + 1; // 计算剩余天数，包括当天
    return remainingDays / endOfMonth.day; // 获取本月最后一天
  }

  //获取权重完整Text内容
  String getWeightText(DateTime date) {
    DateTime endOfMonth = DateTime(date.year, date.month + 1, 0); // 获取本月最后一天
    int remainingDays = endOfMonth.difference(date).inDays + 1; // 计算剩余天数，包括当天
    return '*权重: 剩余$remainingDays天 ÷ ${endOfMonth.day}天 = ${(remainingDays / endOfMonth.day).toStringAsFixed(2)}';
  }
}

class itemWidget extends StatelessWidget {
  final String title;
  final String price;
  bool? intOnly;

  //用于标记区分 1:用电量/2:用水量/0:其他 三个类别
  int? type;

  itemWidget({
    super.key,
    required this.title,
    required this.price,
    this.intOnly,
    this.type,
  }) {
    intOnly ??= false;
    type ??= 0;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 10.h),
      height: 40.h,
      decoration: BoxDecoration(
          color: const Color(0xff6c757d),
          image: DecorationImage(
              image: const AssetImage('assets/images/crossword.png'),
              repeat: ImageRepeat.repeat,
              colorFilter: ColorFilter.mode(
                  Colors.black.withOpacity(0.8), BlendMode.srcIn))),
      child: Stack(
        children: [
          Positioned(
              left: 70.w,
              top: 14.h,
              child: Text(
                '・・・・・・・・・・・・・・・・・・・・・・・・・・・・・',
                style: TextStyle(fontSize: 10.sp),
              )),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                title,
                style: TextStyle(
                    decoration: TextDecoration.none,
                    fontSize: 30.sp,
                    fontFamily: "欢字卡通手书",
                    color: Colors.black87),
              ),
              SizedBox(
                  child: Container(
                decoration: BoxDecoration(
                    color: const Color(0xff6c757d),
                    image: DecorationImage(
                        image: const AssetImage('assets/images/crossword.png'),
                        repeat: ImageRepeat.repeat,
                        colorFilter: ColorFilter.mode(
                            Colors.black.withOpacity(0.8), BlendMode.srcIn))),
                child: Text(
                  type == 0
                      ? price
                      : type == 1
                          ? '$price度'
                          : '$price吨',
                  style: TextStyle(
                      decoration: TextDecoration.none,
                      fontSize: 30.sp,
                      fontFamily: "欢字卡通手书",
                      color: Colors.black87),
                ),
              ))
            ],
          )
        ],
      ),
    );
  }
}

class FullScreenImage extends StatefulWidget {
  final String imagePath;

  const FullScreenImage({super.key, required this.imagePath});

  @override
  State<FullScreenImage> createState() => _FullScreenImageState();
}

class _FullScreenImageState extends State<FullScreenImage> {
  double scale = 1;
  double previousScale = 1;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pop(context);
      },
      onScaleStart: (details) {
        previousScale = scale;
      },
      onScaleUpdate: (details) {
        setState(() {
          scale = previousScale * details.scale;
        });
      },
      child: Container(
        color: Colors.black,
        alignment: Alignment.center,
        child: Hero(
          tag: widget.imagePath,
          child: Transform.scale(
            scale: scale,
            child: Image.file(
              File(widget.imagePath),
              fit: BoxFit.contain,
            ),
          ),
        ),
      ),
    );
  }
}

class ThumbnailImage extends StatelessWidget {
  final String imagePath;

  ThumbnailImage({required this.imagePath});

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<ImageInfo>(
      future: getImageInfo(imagePath),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          final imageInfo = snapshot.data!;
          final double aspectRatio = imageInfo.image.width.toDouble() /
              imageInfo.image.height.toDouble();

          // 根据图片宽高比例判断图片方向
          if (aspectRatio >= 1.0) {
            // 横屏图片
            return AspectRatio(
              aspectRatio: aspectRatio,
              child: Image.file(
                File(imagePath),
                fit: BoxFit.fitWidth, // 适应宽度
              ),
            );
          } else {
            // 竖屏图片
            return AspectRatio(
              aspectRatio: aspectRatio,
              child: Image.file(
                File(imagePath),
                fit: BoxFit.fitHeight, // 适应高度
              ),
            );
          }
        } else {
          return CircularProgressIndicator(); // 显示加载指示器
        }
      },
    );
  }

  Future<ImageInfo> getImageInfo(String imagePath) async {
    final completer = Completer<ImageInfo>();
    final image = Image.file(
      File(imagePath),
      fit: BoxFit.cover,
    );
    image.image.resolve(ImageConfiguration()).addListener(
      ImageStreamListener(
        (info, synchronousCall) {
          completer.complete(info);
        },
      ),
    );
    return completer.future;
  }
}
